import { defineStore } from "pinia";
import {ref, toRefs} from "vue";
import collectionApi from '@/api/collection/index.js';
import LocalStoreUtil from "@/utils/LocalStoreUtil.js";
import CollectionUtil from "@/utils/CollectionUtil.js";
import ResponseUtil from "@/utils/ResponseUtil.js";
import ObjectUtil from "@/utils/ObjectUtil.js";

// 用户相关
const user = ref({
  // 用户登录标识
  authorization: '',
  // 用户详情信息
  info: {
    id: -1,
    avatar: '',
    nickName: '',
    email: '',
    mobile: '',
    collectCount: 0,
    birthday: '',
    registerTime: ''
  },
  method: {
    resetData: () => {
      user.value.authorization = '';
      user.value.info = {
        id: -1,
        avatar: '',
        nickName: '',
        email: '',
        mobile: '',
        collectCount: 0,
        birthday: '',
        registerTime: ''
      }
    }
  }
})

// 搜索相关
const search = ref({
  logId: 0,
  keyword: '搜索',
  defaultSearchEngine: {
    id: 1,
    name: '百度搜索',
    iconUrl: 'http://120.46.171.159:9000/biscuit-tag-page/public/baidu-icon.svg',
    isDefault: true,
    fastKey: 'Alt + 1'
  },
  method: {}
})

// 收藏列表相关
const collect = ref({
  currentItemData: {
    id: 0,
    title: '',
    url: '',
    iconUrl: '',
    iconAlias: '',
    ordered: null,
    isDefault: true,
  },

  method: {
    // 重置收藏项数据
    resetData: () => {
      collect.value.currentItemData = {
        id: 0,
        title: '',
        url: '',
        iconUrl: '',
        iconAlias: '',
        ordered: null,
        isDefault: true,
      }
    }
  }
})

// 收藏列表相关
const collection = ref({
  currentItemData: {
    id: 0,
    title: '',
    url: '',
    iconUrl: '',
    iconAlias: '',
    ordered: 1,
    isDefault: true,
  },
  collectionList: [],
  method: {

    // 加载收藏列表
    loadCollectionList: () => {
      // 判断状态库是否有收藏列表数据，有则则不做任何操作
      if (CollectionUtil.isNotEmpty(collection.value.collectionList)) return;

      // 本地缓存无收藏列表数据，则向服务器请求数据
      if (LocalStoreUtil.isCollectEmpty()) {

        collectionApi.list().then(response => {

          ResponseUtil.data(response).dispose(response => {
            if (response.code === '200') {
              // 设置列表显示状态
              response.data.list.forEach(x => {
                x.displayType = 4;
              });

              LocalStoreUtil.setCollectList(response.data.list);  // 将收藏列表数据存储到本地缓存
              collection.value.collectionList.push(...LocalStoreUtil.getCollectList()); // 将本地缓存中收藏列表数据同步到状态库
              collection.value.method.addCollection();  // 追加新增按钮收藏项
            }
          })

        })

      } else {
        collection.value.collectionList.push(...LocalStoreUtil.getCollectList()); // 同步本地缓存中的收藏列表数据到状态库中
        collection.value.method.addCollection(); // 追加新增按钮收藏项
      }
    },

    // 添加新增收藏项
    addCollection: () => {
      collection.value.collectionList.push({
        id: 99999999,
        isAdd: true,
        isDefault: false
      });
    },

    // 向收藏列表中添加收藏项
    addItem: (data) => {
      // 定义初始下标
      let index = 0;

      // 根据新增收藏项排序值找到需要插入的位置
      for (let i = 0; i < collection.value.collectionList.length; i++) {
        if (!collection.value.collectionList[i].isAdd && !collection.value.collectionList[i].isDefault && collection.value.collectionList[i].ordered > data.ordered) {
          index = i;
          break;
        }
      }

      // 仍然为零则说明是最小的一项，追加在最后即可
      if (index === 0) {
        collection.value.collectionList.splice(collection.value.collectionList.length - 1, 0, data);
      } else {
        collection.value.collectionList.splice(index, 0, data);
      }
    },

    // 根据Id修改收藏项数据
    editItem: (data) => {
      let editIndex = 0;
      for (let i = 0; i < collection.value.collectionList.length; i++) {
        if (collection.value.collectionList[i].id === data.id) {
          editIndex = i;
          break;
        }
      }
      collection.value.collectionList[editIndex] = ObjectUtil.clearRef(data);
    },

    // 根据id删除收藏列表中某个收藏项
    delItemById: (id) => {
      let delIndex = 0;
      // 根据插入收藏项的排序获取到在列表中的下标
      collection.value.collectionList.some((x, currentIndex) => {
        if (x.id === id) {
          delIndex = currentIndex;
          return true;
        }
        return false;
      })
      collection.value.collectionList.splice(delIndex, 1);
    },

    /**
     * 根据id重置指定收藏项状态
     */
    resetItemById: (id) => {
      collection.value.collectionList.forEach(x => {
        if (x.id === id) {
          x.displayType = 4;
        }
      })
    }
  }
})


export const useStore = defineStore('store', () => {

  return {
    search,
    user: user,
    collect,
    collection
  }
})